<!-- 试题录入 -->
<template>
  <div class="questions-new-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{title}}</span>
        </div>
      </template>
      <!-- 试题表单 -->
      <el-form :model="formData" ref="vForm" :rules="rules" label-position="right" label-width="100px" size="medium"
    @submit.prevent>
        <el-form-item label="学科：" prop="subjectID" class="required label-right-align">
          <el-select v-model="formData.subjectID" class="full-width-input" clearable>
            <el-option v-for="(item, index) in subjectIDOptions" :key="index" :label="item.label"
              :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID" class="required label-right-align">
          <el-select v-model="formData.catalogID" class="full-width-input" clearable>
            <el-option v-for="(item, index) in catalogIDOptions" :key="index" :label="item.label"
              :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID" class="required label-right-align">
          <el-select v-model="formData.enterpriseID" class="full-width-input" clearable>
            <el-option v-for="(item, index) in enterpriseIDOptions" :key="index" :label="item.label"
              :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-row class="row-tooltip">
          <el-form-item label="城市：" prop="province" class="required label-right-align">
            <el-select v-model="formData.province" class="full-width-input" clearable>
              <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item"
                :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" label-width="10px" prop="city" class="required">
            <el-select v-model="formData.city" class="full-width-input" clearable>
              <el-option v-for="(item, index) in cityOptions" :key="index" :label="item" :value="item"
            ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="方向：" prop="direction" class="required label-right-align">
          <el-select v-model="formData.direction" class="full-width-input" clearable>
            <el-option v-for="(item, index) in directionOptions" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType" class="required label-right-align">
          <el-radio-group v-model="formData.questionType">
            <el-radio v-for="(item, index) in questionTypeOptions" :key="index" :label="item.value"
              :disabled="item.disabled" style="{display: inline}">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty" class="required label-right-align">
          <el-radio-group v-model="formData.difficulty">
            <el-radio v-for="(item, index) in difficultyOptions" :key="index" :label="item.value"
              :disabled="item.disabled" style="{display: inline}">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 富文本-题干 -->
        <el-form-item label="题干：" prop="question" class="required label-right-align">
          <quill-editor
            v-model:value="formData.question"
            :options="quillState.editorOption"
            :disabled="quillState.disabled"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @ready="onEditorReady($event)"
            @change="onEditorChange($event)"
          />
        </el-form-item>

        <el-form-item label="选项：" prop="formData.radio" class="label-right-align option-flex-coloum" v-if="formData.questionType !=='3'">
          <!-- 单选题 -->
          <el-radio-group v-model="formData.radio" v-if="formData.questionType==='1'">
            <el-radio v-for="(item, index) in optionsOptions" :key="index" :label="item.value" style="{display: block}">{{item.label}}
              <el-input placeholder="" v-model="formData.options[index].title"></el-input>
              <div class="to-file-box">上传图片
                <el-icon><CircleClose /></el-icon>
              </div>
            </el-radio>
            <el-button type="danger" disabled :icon="Plus">增加选项与答案</el-button>
          </el-radio-group>
          <!-- 多选题 -->
          <el-checkbox-group v-model="formData.checkbox" v-else-if="formData.questionType==='2'">
            <el-checkbox v-for="(item, index) in optionsOptions" :key="index" :label="item.value" style="{display: block}">{{item.label}}
              <el-input placeholder="" v-model="formData.options[index].title"></el-input>
              <div class="to-file-box">上传图片
                <el-icon><CircleClose /></el-icon>
              </div>
            </el-checkbox>
            <el-button type="danger" :icon="Plus" @click="addCheckbox">增加选项与答案</el-button>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="解析视频：" prop="videoURL" class="label-right-align">
          <el-input v-model="formData.videoURL" type="text" clearable></el-input>
        </el-form-item>
        <!-- 富文本-答案解析 -->
        <el-form-item label="答案解析：" prop="answer" class="required label-right-align">
          <quill-editor
            v-model:value="formData.answer"
            :options="quillState.editorOption"
            :disabled="quillState.disabled"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @ready="onEditorReady($event)"
            @change="onEditorChange($event)"
            />
        </el-form-item>
        <el-form-item label="题目备注：" prop="remarks" class="label-right-align">
          <el-input type="textarea" v-model="formData.remarks" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="试题标签：" prop="tags" class="label-right-align">
          <el-input v-model="formData.tags" type="text" clearable placeholder="请选择试题标签"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { toRefs, reactive, getCurrentInstance, ref, onMounted, watch } from 'vue'
import { questionType, difficulty, direction } from '@/api/hmmm/constants.js'
import { Plus } from '@element-plus/icons-vue'
import { quillEditor } from 'vue3-quill'
import { simple } from '@/api/hmmm/subjects'
import { list as getDirectoryList } from '@/api/hmmm/directorys.js'
import { list as getCompanyList } from '@/api/hmmm/companys.js'
import { citys, provinces } from '@/api/hmmm/citys'
import { add, detail } from '@/api/hmmm/questions'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
export default {
  components: {
    quillEditor
  },
  props: {},
  setup () {
    const title = ref('')
    const route = useRoute()
    async function getDetail () {
      const { data } = await detail({ id: route.query.id })
      Object.assign(state.formData, data)
      if (data.questionType === '1') {
        state.formData.radio = (state.formData.options.filter(t => t.isRight === 1))[0].code
      } else if (data.questionType === '2') {
        const arr = state.formData.options.filter(t => t.isRight === true || t.isRight === 1)
        state.formData.checkbox = arr.map(t => t.code)
        state.optionsOptions = state.formData.options.map(t => { return { value: t.code, label: t.code + '：' } })
      }
    }
    onMounted(() => {
      title.value = route.query.id ? '试题修改' : '试题录入'
      if (route.query.id) {
        getDetail()
      }
    })
    // 富文本配置项
    const quillState = reactive({
      // content: '<p></p>',
      _content: '',
      editorOption: {
        placeholder: '',
        modules: {}
      },
      disabled: false
    })
    const onEditorBlur = (quill) => {
      console.log('editor blur!', quill)
    }
    const onEditorFocus = (quill) => {
      console.log('editor focus!', quill)
    }
    const onEditorReady = (quill) => {
      console.log('editor ready!', quill)
    }
    const onEditorChange = ({ quill, html, text }) => {
      // console.log('editor change!', quill, html, text)
      state._content = html
    }
    setTimeout(() => {
      state.disabled = true
    }, 2000)

    const state = reactive({
      formData: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: ref('1'),
        difficulty: ref('1'),
        question: ref('<p></p>'),
        // 选项-单选框的值,用来判断isRight
        radio: '',
        checkbox: [],
        options: [{
          code: 'A',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }],
        videoURL: '',
        answer: ref('<p></p>'),
        remarks: '',
        tags: ''
      },
      rules: {
        subjectID: [{
          required: true,
          message: '字段值不可为空'
        }],
        catalogID: [{
          required: true,
          message: '字段值不可为空'
        }],
        enterpriseID: [{
          required: true,
          message: '字段值不可为空'
        }],
        province: [{
          required: true,
          message: '字段值不可为空'
        }],
        city: [{
          required: true,
          message: '字段值不可为空'
        }],
        direction: [{
          required: true,
          message: '字段值不可为空'
        }],
        questionType: [{
          required: true,
          message: '字段值不可为空'
        }],
        difficulty: [{
          required: true,
          message: '字段值不可为空'
        }],
        question: [{
          required: true,
          message: '字段值不可为空'
        }],
        answer: [{
          required: true,
          message: '字段值不可为空'
        }]
      },
      subjectIDOptions: [],
      catalogIDOptions: [],
      enterpriseIDOptions: [],
      provinceOptions: [],
      cityOptions: [],
      directionOptions: direction,
      questionTypeOptions: questionType.map(t => { return { value: t.value + '', label: t.label } }),
      difficultyOptions: difficulty.map(t => { return { value: t.value + '', label: t.label } }),
      optionsOptions: [{
        value: 'A',
        label: 'A：'
      }, {
        value: 'B',
        label: 'B：'
      }, {
        value: 'C',
        label: 'C：'
      }, {
        value: 'D',
        label: 'D：'
      }]
    })
    // 获取学科简单列表
    async function getSubjectList () {
      const { data } = await simple()
      state.subjectIDOptions = data
    }
    onMounted(() => {
      getSubjectList()
      getComList()
      getCityData()
    })
    // 获取目录数据
    async function getDirecList (subjectID) {
      const { data: { items } } = await getDirectoryList({ subjectID })
      state.catalogIDOptions = items.map(t => {
        return { value: t.id, label: t.directoryName }
      }
      )
    }
    // 学科-目录联动
    watch(() => state.formData.subjectID, newValue => {
      state.formData.catalogID = ''
      getDirecList(newValue)
    },
    { deep: true }
    )
    // 获取企业数据
    async function getComList () {
      const { data: { items } } = await getCompanyList()
      state.enterpriseIDOptions = items.map(t => {
        return { value: t.id, label: t.company }
      })
    }
    // 获取省份
    function getCityData () {
      state.provinceOptions = provinces()
    }
    // 选省获取到市
    function handleProvince (province) {
      state.cityOptions = citys(province)
    }
    // 省份-市联动
    watch(() => state.formData.province, newValue => {
      state.formData.city = ''
      handleProvince(newValue)
    },
    { deep: true }
    )
    // 监听选项单选框的值
    watch(() => state.formData.radio, newValue => {
      state.formData.options.forEach(t => {
        if (t.code === newValue) {
          t.isRight = true
        }
      })
    },
    { deep: true }
    )
    // 增加选项与答案
    function addCheckbox () {
      const str = state.optionsOptions[state.optionsOptions.length - 1].value.charCodeAt()
      const value = String.fromCharCode(str + 1)
      state.optionsOptions.push({
        value: value,
        label: value + '：'
      })
      state.formData.options.push({
        code: value,
        title: '',
        img: '',
        isRight: false
      })
    }
    // 监听选项多选框的值
    watch(() => state.formData.checkbox, newValue => {
      console.log('newValue', newValue)
      state.formData.options.forEach(t => {
        if (newValue.includes(t.code)) {
          t.isRight = true
        }
      })
    },
    { deep: true }
    )
    const instance = getCurrentInstance()
    const router = useRouter()
    const submitForm = () => {
      instance.ctx.$refs.vForm.validate(async valid => {
        if (!valid) return
        await add({ ...state.formData })
        ElMessage.success('操作成功')
        router.push('list')
      })
    }
    const resetForm = () => {
      instance.ctx.$refs.vForm.resetFields()
    }

    return {
      ...toRefs(state),
      submitForm,
      resetForm,
      questionType,
      difficulty,
      Plus,
      getSubjectList,
      getDirecList,
      getComList,
      getCityData,
      handleProvince,
      direction,
      addCheckbox,
      title,
      getDetail,
      quillState,
      onEditorBlur,
      onEditorFocus,
      onEditorReady,
      onEditorChange
    }
  }
}
</script>
<style lang="scss">
  .el-input-number.full-width-input,
  .el-cascader.full-width-input {
    width: 100% !important;
  }

  .el-form-item--medium {
    .el-radio {
      line-height: 36px !important;
    }

    .el-rate {
      margin-top: 8px;
    }
  }

  .el-form-item--small {
    .el-radio {
      line-height: 32px !important;
    }

    .el-rate {
      margin-top: 6px;
    }
  }

  .el-form-item--mini {
    .el-radio {
      line-height: 28px !important;
    }

    .el-rate {
      margin-top: 4px;
    }
  }

  .clear-fix:before,
  .clear-fix:after {
    display: table;
    content: "";
  }

  .clear-fix:after {
    clear: both;
  }

  .float-right {
    float: right;
  }

</style>

<style lang="scss" scoped>
  div.table-container {
    table.table-layout {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;

      td.table-cell {
        display: table-cell;
        height: 36px;
        border: 1px solid #e1e2e3;
      }
    }
  }

  div.tab-container {}

  .label-left-align :deep(.el-form-item__label) {
    text-align: left;
  }

  .label-center-align :deep(.el-form-item__label) {
    text-align: center;
  }

  .label-right-align :deep(.el-form-item__label) {
    text-align: right;
  }

  .custom-label {}

  .static-content-item {
    min-height: 20px;
    display: flex;
    align-items: center;

    :deep(.el-divider--horizontal) {
      margin: 0;
    }
  }

  :deep(.el-card__body){
    padding-left: 62px;
  }
  :deep(.el-tooltip__trigger){
    width: 400px;
  }
  :deep(.el-input--suffix){
    width: 400px;
  }
  .row-tooltip :deep(.el-tooltip__trigger) {
    width: 195px;
  }
  .row-tooltip :deep(.el-input--suffix){
    width: 100%;
  }
  :deep(.el-textarea){
    width: 400px;
  }
  .option-flex-coloum :deep(.el-radio-group){
    flex-direction: column;
    align-items: flex-start
  }
  .option-flex-coloum :deep(.el-checkbox-group){
    display: flex;
    flex-direction: column;
    align-items: flex-start
  }
  .option-flex-coloum :deep(.el-radio),
  .option-flex-coloum :deep(.el-checkbox){
    margin-bottom: 48px;
  }
  .to-file-box {
    position: relative;
    width:99px;
    height:61px;
    border:1px dashed #ccc;
    display: inline-flex;
    margin-left: 15px;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    .el-icon{
      position: absolute;
      top: -7px;
      right: -7px;
      font-size: 18px;
    }
  }
  :deep(.ql-snow){
    width: 100%;
  }
  .ql-container{
    height: 190px;
  }
  :deep(.el-form-item__label){
    font-weight: 700;
  }
</style>
